package com.cj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

@Repository//描述dao层实现类对象。就是特殊的@Component
public class DefaultGoodsDao implements GoodsDao{
    private ArrayList<HashMap<String,String>> list = new ArrayList<>();

    @Autowired
    private DataSource dataSource;

    @Override
    public ArrayList<HashMap<String,String>> findGoods(){
        Connection conn = null;
        PreparedStatement pstat = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            pstat = conn.prepareStatement("select * from tb_goods");
            rs = pstat.executeQuery();
//            String key = "";
//            String value = "";
            while(rs.next()){

//                ResultSetMetaData rsd = rs.getMetaData();


//                map.put("id",rs.getString("id"));
//                map.put("name",rs.getString("name"));
//                map.put("remark",rs.getString("remark"));
//                map.put("createdTime",rs.getString("createdTime"));

//                list.add(map);

                this.selectOne(rs);
            }


        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            try {
                this.close(rs,pstat,conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return list;

    }

    private void close(ResultSet rs,PreparedStatement pstat,Connection conn) throws SQLException {
        if (rs != null) rs.close();
        if (pstat != null) pstat.close();
        if (conn != null) conn.close();

    }

    private void selectOne(ResultSet rs){
        try {
            HashMap<String,String> map = new HashMap<>();
            ResultSetMetaData rst = rs.getMetaData();
            for(int i = 1 ; i < rst.getColumnCount() + 1 ; i ++){
                map.put(rst.getColumnName(i),rs.getString(rst.getColumnName(i)));
                System.out.println(rst.getColumnName(i)+"----->"+rs.getString(rst.getColumnName(i)));
            }
            list.add(map);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }


}
